<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Models\PriDeviceInfo;
use DB;

class DonghuangController extends Controller
{
    /**
     * 动环类型
     */
    public function index(Request $request) {
        $config = config('dh.sys');
        $curType = $request->input('type');
        if (!$curType || !array_has($config, $curType)) {
            return $this->error('设备类型不存在');
        }
        $types = $config[$curType];

        //子类型数量
        $subMap = config('dh.subMap');
        $subMainType = array_values(array_unique($subMap));
        $subTypes = [];
        $typeIds = [];
        $group = config('dh.group');
        foreach ($types as $k => $v) {
            if (in_array($v['rvalue'], $subMainType)) {
                $subTypes[] = $v['child'];
            } elseif(array_key_exists($k, $group)){
                 $typeIds = array_merge($typeIds, array_get($group, $k, []));
            }else {
                $typeIds[] = $v['rvalue'];
            }
        }

        $childNum = $this->getChildTypeNum($subMainType, $subTypes);
        // dd($temp);
        $this->attachNum($types, $childNum);
        //主类型数量
        $mainNum = $this->getMainTypeNum($typeIds);
        $this->attachNum($types, $mainNum);
        

        return $this->success('', ['devices' => array_values($types), 'name' => array_get(config('dh.names'), $curType)]);
    }
    
    //子设备数量格式化
    private function getSubNum($childData) {
        if(!$childData) {
            return [];
        }
        $temp = [];
        foreach ($childData as  $v) {
            $v=(array)$v;
            $key1 = $v['tu_TypeId'].$v['tu_SubTypeId'];
            if(!isset($temp[$key1])){
                $temp[$key1] = [];
            }
            if(!in_array($v['tu_pdi_index'], $temp[$key1])) {
                $temp[$key1][] = $v['tu_pdi_index'];
            }
        }
//        $result = [];
//        foreach ($temp as $key => $val) {
//            $result[$key] = count($val);
//        }
        return $temp;
    }
    //获取主设备数量
    private function getMainTypeNum($param) {
        if(empty($param)) {
            return [];
        }
        $devices = PriDeviceInfo::whereIn('dpt_id', $param)
                ->select(['dpt_id', 'pdi_index'])
                ->get();
        $mainTemp = [];
        if ($devices->count()) {
            $mainTemp = $devices->groupBy('dpt_id');
        }
        return $mainTemp;
    }
    //获取子设备数量
    private function getChildTypeNum($subMainType, $subTypes) {
        if(empty($subTypes)) {
            return [];
        }
        $subPdiIndex =  PriDeviceInfo::whereIn('dpt_id', $subMainType)
                ->select(['pdi_index'])
                ->get()->pluck('pdi_index')->toArray();

        $where = [
            ['tu_TypeId', 'in', $subMainType],
            ['tu_SubTypeId', 'in', $subTypes],
            ['tu_pdi_index', 'in', $subPdiIndex],
        ];
        $childData = $this->getSwitch($where);
        $temp = $this->getSubNum($childData);
        return $temp;
    }
    //附加数量给数组
    private function attachNum(&$data, $dataNum) {
        $group = config('dh.group');
        foreach ($data as $k => $val) {
            $groupKey = [];
            if (!isset($data[$k]['num'])) {
                $data[$k]['num'] = 0;
            }
            $groupKey = array_key_exists($k, $group) ? array_get($group, $k):[$k];
            if($dataNum){
                foreach ($groupKey as  $vv) {
                    $data[$k]['num'] += isset($dataNum[$vv]) ? count($dataNum[$vv]) : 0;
                }
            }
        }
    }
    /**
     * 获取设备数据
     */
    protected function getDevices($typeId, $subType=false) {
        if(!$typeId) {
            return [];
        }
        $query = PriDeviceInfo::query();
        $group = config('dh.group');
        if($typeId) {
            if(array_key_exists($typeId, $group)){
                $query->whereIn('dpt_id', array_get($group, $typeId));
            }else{
                $query->where('dpt_id', $typeId);
            } 
        }
        if($subType) {
            $childType = substr($subType, strlen($typeId));
            $where = [
                ['tu_TypeId', '=', $typeId],
                ['tu_SubTypeId', '=', $childType],
            ];
            $sub = $this->getSwitch($where);
            $sub = collect($sub)->pluck('tu_pdi_index')->all();
//            $filepath = base_path().'/storage/logs/phpdevice_'.date('Ymd').'.php';
//            file_put_contents($filepath, "<?php \r\n     ".var_export($sub, true). "; \r\n");
           
            if($sub) {
                $query->whereIn('pdi_index', $sub);
            }
        }
        $devices = $query
                ->select(['AreaId', 'dpt_id', 'pdi_name', 'pdi_index'])
                ->get()
                ->toArray();
                
        $deviceItem = null;
        
        $desc = config('dh.desc');
        
        $map = config('dh.subMap');
        
        foreach ($devices as  $v) {
            $typeId = $v['dpt_id'];
            if($subType && in_array($typeId, $map)) {
                $typeId = $subType;
            }
            $deviceItem[] = [
                'value' => $v['pdi_index'], 
                'label' => $v['pdi_name'], 
                'icon' => array_get($desc, $typeId.'.icon'),
                'areaId' => $v['AreaId'],
                'type' => $typeId,
                'router' => array_get($desc, $typeId.'.router')
            ];
        }


        return $deviceItem;
    }
    
    /**
     * 根据类型获取设备
     * @param Request $request
     */
    public function device(Request $request) {
        $type = $request->input('type', '');
        $postType = $type;
        $map = config('dh.subMap');
        $subType = false;
        if(in_array($type, $map)) {
            $default = 1;
            $subType = $type.$default;
        }
        if(array_key_exists($type, $map)) {
            $subType = $type;
            $type =  $map[$type]; 
        }
        
       $desc = config('dh.desc');
       $groupDesc = config('dh.groupDesc');

        $devices = $this ->getDevices($type, $subType);
        return $this->success('', [ 'devices' => $devices, 'title'=> array_get($desc, $postType.'.label', array_get($groupDesc, $postType)) ]);
    }
    /**
     * 动环数据
     */
    public function realData(Request $request) {
        $pdi = $request->input('pdi',0);
        $reqType = $request->input('type','');
        $info = PriDeviceInfo::find($pdi);
        if(!$info) {
            return $this->error('设备数据不存在');
        }  
        $tables = config('dh.desc');
        $curType = $info->dpt_id;
        if(!$curType) {
            return $this->error('设备类型不存在');
        }
        $default = 1;
        $map = config('dh.subMap');
        if(in_array($reqType, $map)) {
            $reqType = $reqType.$default;
        }
        $table = array_get($tables, ($reqType?$reqType:$curType).'.realtable');
        
        $devices = DB::table($table)->where('pdi_index', '=', trim($pdi))->first();
        if($curType==33){
            $devices = $this->formatReal($devices, $curType);
        }
        $subField = [];
        if($curType==34 && $devices) {
            $childType = substr($reqType, strlen($curType));
            $where = [
                ['tu_TypeId', '=', $curType],
                ['tu_SubTypeId', '=', $childType],
                ['tu_pdi_index', '=', $pdi],
            ];
            $sub = $this->getSwitch($where);
            // $sub = collect($sub)->all();
            $prefix = 'rd_switch';
            $txtFix = '环境开关量';
            foreach ($sub as $v) {
               $toSubCha = $v->tu_SubCha;
               $toSubChaDesc = $v->tu_WarnMo;
               $field = $prefix.$toSubCha;
               $subField[] = [ 'label'=>$toSubChaDesc?$toSubChaDesc:$txtFix.$v, 'value'=>$devices->$field==0 ];
            }
        }
        $title = array_get($tables, $reqType.'.label', array_get($tables, $curType.'.label'));
        
        return $this->success('', [ 'status' => 1, 'devices' => $devices, 'subFields' => $subField, 'title'=>$title, 'pdi_name'=>$info->pdi_name  ]);
    }
    
    /**
     * 获取开关量
     * @param int $type 主类型
     * @param int $childType 子类型
     */
    protected function getSwitch($where) {
        $table = 't_UserDeSubDev';
        $query = DB::table($table);
        foreach ($where as  $val) {
            if($val[1]=='in'){
                $method = 'whereIn';
                $query->whereIn($val[0], $val[2]);
            }else{
                $method = 'where';
                $query = call_user_func_array([$query, $method], $val);
            }
            
        }
        $result = $query->select(['tu_SubCha', 'tu_pdi_index', 'tu_TypeId', 'tu_SubTypeId', 'tu_WarnMo'])->get();
        return $result;
    }
    
        /**
     * 格式化实时数据
     * @param array $data
     * @param string $table
     * @return array
     */
    protected function formatReal($data, $dptId, $prefix = 'rd_') {
     //$filepath = base_path().'/storage/logs/php_'.date('Ymd').'.php';
     //file_put_contents($filepath, "<?php \r\n     ".var_export($data, true). "; \r\n");
        if(!$data) {
            return [];
        }
        $surfix = config('device.surfix')[$dptId];
        $consta = config('device.consta')[$dptId];
        $desc = config('device.desc')[$dptId];
        $numField = $desc['num'];
        $unit = config('device.units')[$dptId];
        $result = [];
        $data = [$data];
        foreach ($data as $item) {
            $num = isset($item->{$numField})?(int)$item->{$numField}:8;
            $num = $num ? $num : 8;
            $params = [];
            for ($i = 1; $i <= $num; $i++) {
                $param = [];
                foreach ($surfix as $k => $v) {
                    $keyPrefix = $prefix . $k . $i;
                    $keyHwarn = $keyPrefix . 'hwarn';
                    $keyLwarn = $keyPrefix . 'lwarn';
                    // $keyPrefix = $prefix . $k . $i;
                    // dd($keyPrefix);
                    $param[$k] = [
                        $k . '_name' => $v,
                        $k . '_value' => $item->$keyPrefix,
                        'hwarn_name' => $v . $i . '上限状态',
                        'hwarn_value' => $item->$keyHwarn,
                        'lwarn_name' => $v . $i . '下限状态',
                        'lwarn_value' => $item->$keyLwarn,
                    ];
                }
                list($constaField, $constaName) = $consta;
                $constaKey = $prefix . $constaField . $i . 'consta';
                $param['consta'] = array_merge([], [
                    'consta_name' => $constaName,
                    'consta_value' => $item->{$constaKey},
                ]);
                $params[] = $param;
            }
            $result['rd_updatetime'] = $item->rd_updatetime;
            $result['rd_NetCom'] = $item->rd_NetCom;
            $result['pdi_index'] = $item->pdi_index;
            $result['num'] = $num;

            foreach ($surfix as $k => $v) {
                $fields[] = $k;
            }
            // $fields[] = 'consta';
            $result['fields'] = $fields;
            $result['name'] = $desc['name'];
            // $item['params'] = $params;
            $result['items'] = $params;
            $result['unit'] = $unit;

            $result['icons'] = config('device.icons');
        }
        // file_put_contents($filepath, "<?php \r\n     ".var_export($result, true). "; \r\n", FILE_APPEND);
        return $result;
    }
    
    /**
     * 保存设备
     * @param Request $request
     * @return array
     */
    public function storeDevice(Request $request)
    {
       $data = $request->input();
       $message = [   
        'pdi_name.required' => '设备名称必须',
        'pdi_name.max' => '设备名称不能超过64个字符',
        
        'pdi_code.required' => '设备编号必须',
        'pdi_code.unique' => '设备编号已存在',
        'pdi_code.max' => '设备编号不能超过64个字符',
        
        'dpt_id.required' => '设备分类编号必须',
        'dpt_id.integer' => '设备分类编号必须是数字',
        'dpt_id.exists' => '设备分类不存在',
           
        'AreaId.required' => '区域必须',
        'AreaId.integer' => '区域必须是数字',
        'AreaId.exists' => '区域不存在',
        ];
        $this->validate($request, [
            'pdi_name' => 'required|max:64',
            'pdi_code' => 'required|max:64|unique:t_prideviceinfo,pdi_code',
            'dpt_id' => 'required|integer|exists:t_devicetype,dt_typeid',
            'AreaId' => 'required|integer|exists:sy_area,AreaId',
        ], $message);
       $data['Co_ID'] = $request->user()->Co_ID;
       $data['pdi_updatetime'] = date('Y-m-d H:i:s');
       $ret = PriDeviceInfo::create($data);
       
       if($ret){
           $this->addAction();
           return $this->success('添加成功');
       }else{
           return $this->error('添加失败');
       }
    }
    /**
     * 更新设备
     * @param resource $request
     * @param int $id
     * @return array
     */
    public function update(Request $request, $id)
    {
       // $deviceType = PriDeviceInfo::findOrFail($id);
       $data = $request->only(['pdi_name']);
       $message = [   
        'pdi_name.required' => '设备名称必须',
        'pdi_name.max' => '设备名称不能超过64个字符',
        ];
        $this->validate($request, [
            'pdi_name' => 'required|max:64',
        ], $message);
       $cid = $request->user()->Co_ID;
       $data['pdi_updatetime'] = date('Y-m-d H:i:s');
       $ret = PriDeviceInfo::where([
           'Co_ID'=>$cid,
           'pdi_index' => $id
       ])->update($data);
       
       if($ret!==false){
           $this->addAction();
           return $this->success('保存成功');
       }else{
           return $this->error('保存失败');
       }
    }
    
    /**
     * 删除设备
     * @param int $id
     * @return array
     */
    public function destroy(Request $request, $id)
    {
       // $deviceType = PriDeviceInfo::findOrFail($id);
       $cid = $request->user()->Co_ID;
       $ret = PriDeviceInfo::where([
           'Co_ID'=>$cid,
           'pdi_index' => $id
       ])->delete();
       if($ret){
           $this->addAction();
           return $this->success('删除成功');
       }else{
           return $this->error('删除失败');
       }
    }
       
    /**
     * 上传测试
     * @param Request $request
     */
  public function store(Request $request)
 {
 
    $file=$request->file('logo');
    // dd($file);
    $content = file_get_contents($file->getRealPath());
    //文件路径
    $filepath = base_path().'/storage/upload/attach/'.date('YmdHis').'.png';
    //提取base64字符
    // $imgdata = substr($content,strpos($content,",") + 1);
    file_put_contents($filepath, $content);

 }
}
